<template>
  <el-container>
    <el-row>
      <el-col>
        <el-form :model="form" label-width="80px">
          <el-form-item label="name"> <el-input type="text" v-model="form.name"></el-input> </el-form-item>
          <el-form-item label="password">
            <el-input type="text" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="photo">
            <el-upload
              class="avatar-uploader"
              action="/"
              :show-file-list="false"
              :on-change="changeFile"
              :auto-upload="false"
              :multiple="true"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button @click="userRegister">注册</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '', // 后台返回的头像图片的url
      photoFile: {}, // 头像
      form: {
        name: '',
        password: ''
        //不加头像的属性
      }
    }
  },
  methods: {
    userRegister() {
      let myFormData = new FormData()
      // myFormData.append('后端接口的参数名', this.form.name)
      myFormData.append('username', this.form.name)
      myFormData.append('password', this.form.password)
      myFormData.append('file', this.photoFile)
      // myFormData.append('file',this.photoFile2)  // 多文件是给同一个key添加值。

      this.$axios({
        url: '/register',
        method: 'post', // 文件上传，必须是post.
        data: myFormData // 直接白formData对象做参数对象
        // headers: {
        //   'content-type': 'multiple/form-data'
        // }
      })
        .then()
        .catch()
    },
    changeFile(file) {
      console.log(file.raw) // File{}
      // console.log(fileList)
      this.photoFile = file.raw

      // 添加预览
      // this.imageUrl = 'base64://'
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
